<template>
  <div>
    <PageTitleSearch
      :title="title"
      :hotelList="hotelList"
      :currentHotel="currentHotel"
      v-model:lastMonth="lastMonth"
      :currentAcc="currentAcc"
      @hotel-change="handleSelectChange"
      @date-change="handleDateSelect"
      @acc-change="handleAccSelect"
    />
    <div class="main-content">
      <div class="total-wrap">
        <div class="card-double">
          <div class="card-point">
            <span class="card-title">总收入</span>
            <div class="card-num-wrap"
              ><span class="unline">{{ infoData.income }} </span>
              <span class="card-unit">万元</span>
            </div>
          </div>
          <div class="card-remark">
            <span class="card-budget">预算：{{ infoData.incomeBudget }}, </span>
            <svg width="10" height="10">
              <polygon :points="getTrianglePoint(infoData.incomeBudget > 0)" :style="{ fill: getColor(infoData.incomeBudget > 0) }" />
            </svg>
            <span
              :style="{
                color: getColor(infoData.incomeBudget > 0),
              }"
            >
              {{ infoData.budgetPercent }}</span
            >
            <span class="info-dash-line"></span>
            <span
              >去年：{{ infoData.lastYearDiff }},
              <svg width="10" height="10">
                <polygon
                  :points="getTrianglePoint(infoData.lastYearDiff > 0)"
                  :style="{
                    fill: getColor(infoData.lastYearDiff > 0),
                  }"
                />
              </svg>
              <span
                :style="{
                  color: getColor(infoData.lastYearDiff > 0),
                }"
              >
                {{ infoData.lastYearDiffPercent }}</span
              ></span
            >
          </div>
        </div>
        <div class="card-solid-line"></div>
        <div class="card-double">
          <div class="card-point">
            <span class="card-title">人工成本</span>
            <span class="card-sub-title">（正式+外包）</span>
            <div class="card-num-wrap"
              ><span class="unline">{{ infoData.fte }} </span>
              <span class="card-unit">万元</span>
            </div>
          </div>
          <div class="card-remark">
            <span class="card-budget">预算：{{ infoData.fteBudget }}, </span>
            <svg width="10" height="10">
              <polygon :points="getTrianglePoint(infoData.fteBudget > 0)" :style="{ fill: getColor(infoData.fteBudget > 0) }" />
            </svg>
            <span
              :style="{
                color: getColor(infoData.fteBudget > 0),
              }"
            >
              {{ infoData.fteBudgetPercent }}</span
            >
            <span class="info-dash-line"></span>
            <span
              >去年：{{ infoData.fteLastYearDiff }},
              <svg width="10" height="10">
                <polygon
                  :points="getTrianglePoint(infoData.fteLastYearDiff > 0)"
                  :style="{
                    fill: getColor(infoData.fteLastYearDiff > 0),
                  }"
                />
              </svg>
              <span
                :style="{
                  color: getColor(infoData.fteLastYearDiff > 0),
                }"
              >
                {{ infoData.fteLastYearDiffPercent }}</span
              ></span
            >
          </div>
        </div>
      </div>
      <a-row :gutter="12" style="margin-bottom: 10px">
        <a-col :span="8">
          <FlexCard title="人工成本" subtitle="（正式工）" :loading="loading" :dataList="staffData" :is-center-title="true">
            <BarSingleImg v-if="staffData.length > 0" :dataList="staffData" :show-unit="false" unit="万元" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="人工成本" subtitle="（正式工+外包工）" :loading="loading" :dataList="staffData" :is-center-title="true">
            <BarSingleImg v-if="fteData.length > 0" :dataList="fteData" :show-unit="false" unit="万元" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard title="人工成本率" subtitle="（正式工+外包工）" :loading="loading" :dataList="staffData" :is-center-title="true">
            <RingImg v-if="fteRateData.length > 0" :dataList="fteRateData" />
          </FlexCard>
        </a-col>
      </a-row>
      <FlexCard :dataList="tableData" style="margin-bottom: 10px">
        <TableCard :dataList="tableData" :columns="columns" :scroll="tableHigh" :show-unit="false" :loading="loading" />
      </FlexCard>
      <ReportRemarkCard :loading="loading" v-if="reportCode" title="说明" :reportCode="reportCode" :reportName="reportName" />
    </div>
  </div>
</template>
<script>
  import dayjs from 'dayjs';

  import * as MathUtil from '/@/utils/MathUtil';
  import * as Color from '/@/utils/ColorDefault';
  import { defHttp } from '/@/utils/http/axios';
  import * as Constant from '/@/utils/Constant';

  import FlexCard from '@/views/applications/ui/FlexCard.vue';
  import RingImg from '@/views/applications/ui/RingImg.vue';
  import ReportRemarkCard from '@/views/applications/ui/ReportRemarkCard.vue';
  import BarSingleImg from '@/views/applications/ui/BarSingleImg.vue';
  import TableCard from '@/views/applications/ui/SubjectFteTable.vue';
  import PageTitleSearch from '@/views/applications/ui/PageTitleSearch.vue';
  const REPORT_NAME = '酒店月度人力成本（项目）';
  const REPORT_CODE = 'hotel-month-single-fte';
  const APIS = {
    month: 'getHotelMonthSubjectFte',
    year: 'getHotelMonthAccSubjectFte',
  };
  const INCOME_APIS = {
    month: 'getHotelMonthReportFte',
    year: 'getHotelMonthReportAccFte',
  };
  export default {
    name: REPORT_NAME,

    components: {
      FlexCard,
      RingImg,
      ReportRemarkCard,
      BarSingleImg,
      TableCard,
      PageTitleSearch,
    },

    data() {
      return {
        title: '人工成本',
        reportCode: '',
        reportName: '',
        accList: [
          { label: '当月', value: 'month' },
          { label: '当年', value: 'year' },
        ],
        currentAcc: 'month',
        currentAccName: '当月',
        reportCodeY: '',
        reportNameY: '',
        loading: false,
        tableHigh: { x: '100%', y: 600 },
        lastMonth: dayjs().subtract(1, 'month').format('YYYYMM'),
        hotelList: [],
        subjectList: [],
        currentHotel: {},
        infoData: {
          fte: '',
          fteBudget: '',
          gop: '',
          hotelCode: '',
          hotelName: '',
          income: '',
          incomeBudget: '',
          lFte: '',
          lGop: '',
          lIncome: '',
          lStaff: '',
          staff: '',
          staffBudget: '',
        },
        infoDataY: '',
        staffData: [],
        fteData: [],
        fteRateData: [],
        columns: [
          {
            title: '科目',
            dataIndex: 'subjectName',
            width: 280,
            fixed: 'left',
          },
          {
            title: '实际',
            dataIndex: 'actual',
            width: 80,
            align: 'right',
            customRender: (val, record) => this.colRender(val, record),
          },
          {
            title: '预算',
            dataIndex: 'budget',
            width: 80,
            align: 'right',
            customRender: (val, record) => this.colRender(val, record),
          },
          {
            title: '差异率',
            dataIndex: 'budgetDiffRate',
            width: 100,
            align: 'right',
            customRender: (val) => MathUtil.percent2DFormatter(val, 0),
          },
          {
            title: '去年',
            dataIndex: 'lActual',
            width: 80,
            align: 'right',
            customRender: (val, record) => this.colRender(val, record),
          },
          {
            title: '差异率',
            dataIndex: 'yearDiffRate',
            width: 100,
            align: 'right',
            customRender: (val) => MathUtil.percent2DFormatter(val, 0),
          },
        ],
        tableData: [],
      };
    },

    created() {
      Promise.all([
        defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }),
        defHttp.post({
          url: 'data/query',
          data: {
            labelCode: 'getHotelOptsubject',
            sqlParams: [],
            pageIndex: 1,
            pageSize: 1000,
          },
        }),
      ]).then((res) => {
        const [hotelRes, subjectRes] = res;
        if (hotelRes.success && hotelRes.result.length > 0) {
          const dataList = hotelRes.result;
          this.hotelList = hotelRes.result.map((s) => {
            return { label: s.name, value: s.code };
          });
          console.log(this.hotelList);
          const currentHotelCode = this.$route.query.hotelCode || localStorage.getItem(Constant.STORAGE_HOTEL_NAME);
          if (currentHotelCode && dataList.filter((d) => d.code === currentHotelCode).length > 0) {
            this.currentHotel = dataList.filter((d) => d.code === currentHotelCode)[0];
          } else {
            this.currentHotel = {
              code: hotelRes.result[0].code,
              name: hotelRes.result[0].name,
            };
          }
        }
        if (subjectRes.datas.success && subjectRes.datas.data) {
          this.subjectList = subjectRes.datas.data;
        }
        if (this.hotelList && this.subjectList) {
          this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
          this.reportName = `${REPORT_NAME}-${this.currentAccName}-${this.currentHotel.name}-${this.lastMonth}`;
          this.fetchData();
        }
      });
    },

    methods: {
      getTrianglePoint(isUp) {
        return isUp ? '5,0 0,10 10,10' : '0,0 10,0 5,10';
      },

      getColor(rise = true) {
        return rise ? Color.COLOR_GREEN : Color.COLOR_RED;
      },
      fetchData() {
        this.loading = true;
        console.log('22222222222222222');

        Promise.all([
          defHttp.post({
            url: 'data/query',
            data: {
              labelCode: INCOME_APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          }),
          defHttp.post({
            url: 'data/query',
            data: {
              labelCode: APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          }),
        ]).then((res) => {
          const [incomeRes, subjectRes] = res;
          if (incomeRes.datas.success && incomeRes.datas.data.length > 0) {
            const data = incomeRes.datas.data[0];
            console.log('data', data);

            this.wrapData(data);
          } else {
            this.infoData = {};
            this.staffData = [];
            this.fteData = [];
            this.fteRateData = [];
          }
          if (subjectRes.datas.success && subjectRes.datas.data.length > 0) {
            const data = subjectRes.datas.data;
            this.tableData = this.generatData(data);
          } else {
            this.tableData = [];
          }
          localStorage.setItem(Constant.STORAGE_HOTEL_NAME, this.currentHotel.code);
          this.loading = false;
        });
      },
      generatData(datas) {
        const subjects = datas.map((s) => s.subjectCode);
        let dataList = this.subjectList
          .filter((s) => subjects.includes(s.code) && !['09', '01'].includes(s.code))
          .map((s) => {
            let d = {
              subjectCode: s.code,
              subjectName: s.name,
              calMode: s.calMode,
              formula: s.formula,
              showFormatter: s.showFormatter,
            };
            if (s.calMode === 'DEFAULT') {
              const i = datas.filter((i) => i.subjectCode === s.code);
              if (i.length > 0) {
                d = {
                  ...d,
                  actual: i[0].actual,
                  budget: i[0].budget,
                  lActual: i[0].lActual,
                };
              }
            }
            return d;
          });

        dataList.forEach((s) => {
          if (s.calMode === 'AUTO') {
            ['actual', 'budget', 'lActual'].forEach((k) => {
              const replacedFormula = s.formula.replace(/#\{(\w+)\}/g, (_, code) => {
                const sList = datas.filter((l) => l.subjectCode === code);
                return sList.length > 0 ? (Number(sList[0][k]) >= 0 ? Number(sList[0][k]) : `(${sList[0][k]})`) : 0;
              });
              s[k] = eval(replacedFormula) || 0;
            });
          }
        });
        return dataList.map((s) => this.wrapSubjectData(s));
      },
      colRender(val, record) {
        if (record.showFormatter) {
          const [methodName] = record.showFormatter.split('|');
          if (typeof MathUtil[methodName] === 'function') {
            return MathUtil[methodName](val, 0);
          }
        }
        return val;
      },
      wrapData(data) {
        // fte: 0;
        // fteBudget: 1821927.33;
        // gop: 0;
        // hotelCode: 'H0026';
        // hotelName: '佛山东平保利洲际酒店';
        // income: 0;
        // incomeBudget: 4792514.23;
        // lFte: 122000;
        // lGop: 2252995.66;
        // lIncome: 6705079.62;
        // lStaff: 82000;
        // staff: 0;
        // staffBudget: 1523880.73;
        this['infoData'] = {
          income: MathUtil.currencyWNFormatter(data.income, 0),
          incomeBudget: MathUtil.currencyWNFormatter(data.incomeBudget, 0),
          budgetPercent: MathUtil.diffPercent2Formatter(data.income, data.incomeBudget, 1),
          lastYearDiff: MathUtil.currencyWNFormatter(data.lIncome, 0),
          lastYearDiffPercent: MathUtil.diffPercent2Formatter(data.income, data.lIncome, 1),
          fte: MathUtil.currencyWNFormatter(data.fte, 0),
          fteBudget: MathUtil.currencyWNFormatter(data.fteBudget, 0),
          fteBudgetPercent: MathUtil.diffPercent2Formatter(data.fte, data.fteBudget, 1),
          fteLastYearDiff: MathUtil.currencyWNFormatter(data.fte, 0),
          fteLastYearDiffPercent: MathUtil.diffPercent2Formatter(data.fte, data.lFte, 1),
        };
        this['staffData'] = [
          {
            name: '实际',
            value: data.staff,
            color: Color.COLOR_BLUE,
          },
          {
            name: '预算',
            value: data.staffBudget,
            color: Color.COLOR_PURPLE,
          },
          {
            name: '去年',
            value: data.lStaff,
            color: Color.COLOR_WARN,
          },
        ];
        this['fteData'] = [
          {
            name: '实际',
            value: data.fte,
            color: Color.COLOR_BLUE,
          },
          {
            name: '预算',
            value: data.fteBudget,
            color: Color.COLOR_PURPLE,
          },
          {
            name: '去年',
            value: data.lFte,
            color: Color.COLOR_WARN,
          },
        ];
        this['fteRateData'] = [
          {
            name: '去年',
            value: MathUtil.safeDivide(data.lFte, data.lIncome),
            color: Color.COLOR_WARN,
          },
          {
            name: '预算',
            value: MathUtil.safeDivide(data.fteBudget, data.incomeBudget),
            color: Color.COLOR_PURPLE,
          },
          {
            name: '实际',
            value: MathUtil.safeDivide(data.fte, data.income),
            color: Color.COLOR_BLUE,
          },
        ];
      },
      wrapSubjectData(data) {
        return {
          ...data,
          budgetDiffRate: MathUtil.diff(data.actual, data.budget), // 差异率
          yearDiffRate: MathUtil.diff(data.actual, data.lActual), // 差异率
          budgetDiff: MathUtil.currencyWNFormatter(data.actual - data.budget, 0),
          yearDiff: MathUtil.currencyWNFormatter(data.actual - data.lActual, 0),
        };
      },
      handleSelectChange(value) {
        this.currentHotel = {
          code: value,
          name: this.hotelList.filter((h) => h.value === value)[0].label,
        };
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${this.currentAccName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      isMonthDisabled(current) {
        const lastMonth = dayjs().subtract(1, 'month');
        return current.isAfter(lastMonth);
      },
      handleDateSelect() {
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${this.currentAccName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      handleAccSelect(value) {
        this.currentAcc = value;
        this.currentAccName = this.accList.filter((h) => h.value === value)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${this.currentAccName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },

      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
    },
  };
</script>

<style lang="less" scoped>
  .total-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    border-radius: 0.55rem;
    padding: 2px 10px;
    margin-bottom: 10px;
  }
  .main-content {
    padding: 12px 0;

    &-title {
      &-custom {
        color: #00b578;
      }
    }
  }

  .card-double {
    display: flex;
    justify-content: space-between;

    &-item {
      flex-basis: 48%;
    }
  }

  .card-point {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
  }
  .card-remark {
    font-size: 12px;
    display: flex;
    align-items: center;
    // text-align: right;
    margin-left: 10px;
  }
  .card-title {
    margin-right: 10px;
  }
  .card-num-wrap {
    display: flex;
    align-items: center;
  }
  .card-unit {
    font-size: 12px;
    padding-left: 5px;
  }
  .card-budget {
    padding-right: 5px;
  }
  .interval-area {
    margin-bottom: 12px;
  }
  .dash-line {
    border-left: 1px dashed #d9d9d9;
  }
  .title-name {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 36px;
    background: #ffffff;
    -webkit-box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
    box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
    border-radius: 0.5rem;
    font-size: 16px;
    font-weight: 600;
    .title-name-unit {
      font-weight: 400;
    }
  }

  .select-title-space {
    width: 120px;
    margin-right: 12px;

    &:last-child {
      margin-right: 20px;
    }
  }

  ::v-deep .select-title {
    .ant-select-selection-item {
      color: #ffffff;
      font-size: 14px;
    }
  }

  ::v-deep .select-title .van-cell {
    color: hsl(217, 16%, 60%);
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding: unset;
    -webkit-box-pack: end;
    -ms-flex-pack: end;
    justify-content: flex-end;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    position: relative;
    background-color: #112c4d;
  }

  ::v-deep .a-mobile-select .van-cell__value {
    color: #ffffff;
    font-size: 18px;
    font-weight: 500;
    padding-right: 0.5rem;
    text-align: center;
    display: -webkit-box;
    overflow: hidden;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
  }

  ::v-deep .a-mobile-select .van-cell .select-suffix-icon {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    width: 1.25rem;
    height: 1.25rem;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    font-size: 1rem;
    color: #8894a8;
  }
  .popup-right {
    width: auto;

    &-content {
      height: 800px;
      width: 318px;

      &-oprate {
        display: flex;
        padding: 16px;
        justify-content: center;

        &-item {
          width: 100%;
          margin-right: 10px;
        }

        &-item:last-child {
          margin-right: 0;
        }
      }
    }
  }

  @media @desktop {
    .main-frame-desktop-header {
      padding: 1rem;
      background: #fff;
      overflow: hidden;
    }

    .a-layout-form-vertical,
    .a-layout-form-horizontal {
      width: 30rem;
      margin: 0 auto 5rem auto;
    }

    .a-layout-form-inline__warn {
      color: #ffb829;
      text-align: center;
    }

    .a-layout-form-inline .a-basic-layout-form-button button {
      min-width: 5rem;
      margin-right: 0.5rem;
    }

    .echarts {
      width: 100%;
      height: 240px;
    }

    .card-custom .echarts {
      width: 100%;
      height: 160px;
    }

    .row-left {
      flex: 4;
    }
    .row-right {
      flex: 1;
    }
    .flex-height {
      height: 470px;
    }
    .table-height {
      height: 660px;
    }
    ::v-deep .card-custom .ant-card-body {
      padding: 4px 8px 4px 8px;
      zoom: 1;
    }

    .card-point {
      // height: 65px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
    }
    .card-remark {
      font-size: 12px;
      text-align: right;
    }
    .card-title {
      margin-left: 6px;
      display: flex;
      flex-direction: column;
      align-items: left;
      justify-content: center;
      span {
        line-height: 1.4;
      }
    }
    .card-sub-title {
      font-size: 11px;
      font-weight: 400;
    }
    .unline {
      margin-right: 10px;
      // text-decoration: underline;
    }
  }
  .info-dash-line {
    border-left: 1px dashed rgba(0, 0, 0, 0.5);
    // width: 1px;
    height: 19px;
    margin: 0 5px;
  }
  .card-solid-line {
    border-left: 1px solid rgba(0, 0, 0, 0.5);
    // width: 1px;
    height: 19px;
    margin: 0 25px;
  }
</style>
